package com.zhomboin.config;

import com.zhomboin.common.excaption.BusinessException;
import com.zhomboin.domain.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.validation.FieldError;

import java.io.IOException;
import java.sql.SQLException;
import java.util.stream.Collectors;

@Slf4j
@Configuration
public class GlobalExceptionHandler {

    // 处理业务异常
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<Result<?>> handleBusinessException(BusinessException ex) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(Result.error(ex.getCode(), ex.getMessage()));
    }

    // 处理参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Result<?>> handleValidationException(MethodArgumentNotValidException ex) {
        String errorMsg = ex.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));
        return ResponseEntity.badRequest()
                .body(Result.error(400, "参数错误: " + errorMsg));
    }

    // 处理其他所有异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Result<?>> handleGlobalException(Exception ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Result.error(500, "服务器内部错误: " + ex.getMessage()));
    }

    @ExceptionHandler(IOException.class)
    public ResponseEntity<Result<?>> handleIOException(IOException ex) {
        log.error("文件操作异常", ex);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Result.error(1003, "文件系统错误: " + ex.getMessage()));
    }

    @ExceptionHandler(SQLException.class)
    public ResponseEntity<Result<?>> handleSQLException(SQLException ex) {
        log.error("数据库操作异常", ex);
        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(Result.error(1004, "数据库错误: " + ex.getMessage()));
    }
}
